<?php

/**
 * @author Dream-Seeker
 * @copyright 2015 shiyichuangxiang.com
 */

namespace Phone\Controller;

use Think\Controller;
use Common\Controller\PhoneController;

class PayWechatController extends PhoneController
{

    /**
     * 初始化，调用支付宝核心类库
     */
    public function _initialize()
    {
        vendor('PayWechat.PayNotifyCallBack');
        vendor('PayWechat.Weixin');

    }


    // 公共组装参数
    public function commons($type = '')
    {
        $order_id = I('get.order_id', 0);
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $model = $OrderObj->where(Array('order_id' => $order_id))->find();
        if (empty($model)) {
            $this->redirect('Member/index');
        }

        if ($model['status_pay'] == 3) {
            $this->redirect('Member/myorder');
            exit();
        }

        if ($type == 'JSAPI') {
            $openid = session('openid');
        }

        $weixin_config = C('weixin_config');
        $order_no = $model['order_no'] . '_' . time();
        $total_need_pay = $model['total'] - $model['total_discount'] - $model['total_pay'] - $model['total_pay_money'] - $model['total_pay_point'] - $model['total_pay_yhq'];
        $this->total_need_pay = $total_need_pay;


        $this->title = '订单编号：' . $model['order_no'];
        $this->order_no = $model['order_no'];
        $this->order_id = $order_id;
        $this->success_page = $weixin_config['successpage2'];
        $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
        $headers[] = 'Connection: Keep-Alive';
        $headers[] = 'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3';
        $headers[] = 'Accept-Encoding: gzip, deflate';
        $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0';

        $userip = $this->get_client_ip2();
        $appid = $weixin_config['APPID'];
        $mch_id = $weixin_config['MCHID'];
        $key = $weixin_config['KEY'];

        $nonce_str = MD5($order_no);
        $total_fee = $total_need_pay * 100;
        $spbill_create_ip = $userip;
        $notify_url = $weixin_config['notify_url2'];
        $trade_type = 'MWEB';
        $body = "百宝库商城订单支付";
        $scene_info = '{"h5_info":{"type":"Wap","wap_url":"' . C('WEB_URL') . '","wap_name":"支付"}}';

        if ($type == 'JSAPI') {
            $signA = "appid=$appid&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&openid=$openid&out_trade_no=$order_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
        } else {
            $signA = "appid=$appid&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$order_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
        }
        $strSignTmp = $signA . "&key=$key";
        $sign = strtoupper(MD5($strSignTmp));

        if ($type == 'JSAPI') {
            $post_data = "<xml><appid>$appid</appid><body>$body</body><mch_id>$mch_id</mch_id><nonce_str>$nonce_str</nonce_str><notify_url>$notify_url</notify_url><openid>$openid</openid><out_trade_no>$order_no</out_trade_no><scene_info>$scene_info</scene_info><spbill_create_ip>$spbill_create_ip</spbill_create_ip><total_fee>$total_fee</total_fee><trade_type>$trade_type</trade_type><sign>$sign</sign>
  </xml>";
        }else{
            $post_data = "<xml><appid>$appid</appid><body>$body</body><mch_id>$mch_id</mch_id><nonce_str>$nonce_str</nonce_str><notify_url>$notify_url</notify_url><out_trade_no>$order_no</out_trade_no><scene_info>$scene_info</scene_info><spbill_create_ip>$spbill_create_ip</spbill_create_ip><total_fee>$total_fee</total_fee><trade_type>$trade_type</trade_type><sign>$sign</sign>
  </xml>";
        }

        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $dataxml = $this->http_post($url, $post_data, $headers);
        header("content-type:text/html;charset=utf-8");
        return (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA);
    }


    function pay()
    {
        if (is_weixin()) {
            if (session('openid')) {
                return $this->payWechat();
            }
            return redirect('/Phone/Index/index');
        }

        $objectxml = $this->commons();

        if ($objectxml['return_code'] == 'SUCCESS') {
            $mweb_url = $objectxml['mweb_url'];
            $this->mweb_url = $mweb_url;
        } else {
            $this->mweb_url = $this->success_page;
        }

        $this->display();
    }


    function payWechat()
    {
        $order_id = I('get.order_id', 0);
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $model = $OrderObj->where(Array('order_id' => $order_id))->find();
        $openid = session('openid');
        $weixin_config = C('weixin_config');
        $order_no = $model['order_no'] . '_' . time();
        $total_need_pay = $model['total'] - $model['total_discount'] - $model['total_pay'] - $model['total_pay_money'] - $model['total_pay_point'] - $model['total_pay_yhq'];
        $this->total_need_pay = $total_need_pay;
        $this->title = '订单编号：' . $model['order_no'];
        $this->order_no = $model['order_no'];
        $this->order_id = $order_id;
        $this->success_page = $weixin_config['successpage2'];
        $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
        $headers[] = 'Connection: Keep-Alive';
        $headers[] = 'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3';
        $headers[] = 'Accept-Encoding: gzip, deflate';
        $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0';

        $userip = $this->get_client_ip2();
        $appid = $weixin_config['APPID'];
        $mch_id = $weixin_config['MCHID'];
        $key = $weixin_config['KEY'];

        $nonce_str = MD5($order_no);
        $total_fee = $total_need_pay * 100;
        $spbill_create_ip = $userip;
        $notify_url = $weixin_config['notify_url2'];
        $trade_type = 'JSAPI';
        $body = "百宝库商城订单支付";
        $scene_info = '{"h5_info":{"type":"Wap","wap_url":"' . C('WEB_URL') . '","wap_name":"支付"}}';

        $signA = "appid=$appid&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&openid=$openid&out_trade_no=$order_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";

        $strSignTmp = $signA . "&key=$key";
        $sign = strtoupper(MD5($strSignTmp));

        $post_data = "<xml><appid>$appid</appid><body>$body</body><mch_id>$mch_id</mch_id><nonce_str>$nonce_str</nonce_str><notify_url>$notify_url</notify_url><openid>$openid</openid><out_trade_no>$order_no</out_trade_no><scene_info>$scene_info</scene_info><spbill_create_ip>$spbill_create_ip</spbill_create_ip><total_fee>$total_fee</total_fee><trade_type>$trade_type</trade_type><sign>$sign</sign>
  </xml>";

        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $dataxml = $this->http_post($url, $post_data, $headers);

        header("content-type:text/html;charset=utf-8");

        $xmlarray  = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA);


        $data["appId"] = $xmlarray['appid'];
        $data["timeStamp"] = time();
        $data["nonceStr"] = $this->createNoncestr();
        $data["package"] = "prepay_id=".$xmlarray['prepay_id'];
        $data["signType"] = "MD5";

        $singA = 'appId='.$data['appId'].'&nonceStr='.$data['nonceStr'].'&package='.$data['package'].'&signType='.$data['signType'].'&timeStamp='.$data['timeStamp'].'&key='.$weixin_config['KEY'];

        $data['paySign'] = strtoupper(MD5($singA));

        $this->assign('pay_data', json_encode($data));
        $this->display('Check/payWechat');
    }


    function wxnotify_h5()
    {
        $log_name = "Public/paywechat2/notify_url.log"; //log文件路径
        $this->log_result($log_name, "【接收到的notify开始】:\n签名开始\n");
        $notify = new \Vendor\PayWechat\PayNotifyCallBack();
        $xml = file_get_contents("php://input");
        $array = $notify->xmlToArray($xml);
        if ($array['result_code'] == 'SUCCESS' && $array['return_code'] == 'SUCCESS') {
            $OrderObj = new \Fwadmin\Model\OrderModel();
            $out_trade_no = $array['out_trade_no'];

            $out_trade_no2 = explode('_', $out_trade_no);//防止微信提示重复提交订单支付
            $out_trade_no = $out_trade_no2[0];//订单号
            $model = $OrderObj->where(Array('order_no' => $out_trade_no))->find();
            if ($model['status_pay'] == 3) {
                exit();//如果已经更新订单状态，就不用再继续运行下面的了
            }
            $order_id = $model['order_id'];
            $payment = 'H5微信';
            $money = $model['total'] - $model['total_discount'] - $model['total_pay'] - $model['total_pay_money'] - $model['total_pay_point'] - $model['total_pay_yhq'];

            $OrderObj->pay_3($order_id, $payment, $money);


            $log_name = "Public/paywechat2/" . $out_trade_no . "_" . date('YmdHis') . ".log";
            $this->log_result($log_name, "[支付成功]");


        } else {
            $this->log_result($log_name, "【接收到的notify签名】:\n签名失败\n");
        }

    }


    function http_post($url = '', $post_data = array(), $header = array(), $timeout = 30)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

        $response = curl_exec($ch);

        curl_close($ch);

        return $response;
    }


    function get_client_ip2()
    {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {

            $ip = getenv('HTTP_CLIENT_IP');

        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {

            $ip = getenv('HTTP_X_FORWARDED_FOR');

        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {

            $ip = getenv('REMOTE_ADDR');

        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {

            $ip = $_SERVER['REMOTE_ADDR'];

        }
        return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
    }



    // 随机生成字符串
    function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++)
        {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }


    public function wechat_pay($order_id)
    {
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $status_pay = $OrderObj->where(array('order_id' => $order_id))->getField('status_pay');
        if ($status_pay == 3) {
            echo '1';
        }
    }

    function log_result($file, $word)
    {
        $fp4 = fopen($file, "r"); //只读打开模板,底部;
        $str = fread($fp4, filesize($file)); //读取模板内容
        $str = $str . "\n执行日期：" . date("Y-m-d H:i:s") . "\n" . $word . "\n\n";
        $handle = fopen($file, "w"); //不存在就创建;,创建页面
        fwrite($handle, $str);
    }

}
